<template>
  <el-dialog
    v-model="visible"
    :show-close="false"
    :width="1200"
    style="border-radius: 8px; padding: 24px"
    :close-on-click-modal="true"
    :z-index="900">
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <div class="header-left">{{ publishTitle }}</div>
        <div class="header-right">
          <CheckBox v-model="formData.disable_nex" label="Disable Nex" />
          <el-tooltip
            effect="dark"
            raw-content
            content="<div>By clicking the box, you agree </div>
                <div>Nexbie NOT to sell the physical </div>
                <div>copy of your design</div>"
            placement="top">
            <HelpIcon class="help-icon" />
          </el-tooltip>
          <el-button
            type="primary"
            @click="handlePublish"
            class="publish-btn"
            :disabled="isPublishDisabled">
            Publish
            <SvgIcon name="ai-post" size="24" />
          </el-button>
        </div>
        <SvgIcon name="ai-close" size="24" class="close-icon" @click="close" />
      </div>
    </template>

    <div class="dialog-content">
      <!-- 第二行内容 -->
      <div class="content-row">
        <!-- 左侧图片 -->
        <div class="image-container">
          <img
            v-if="props.promptMode"
            :src="formData.imageUrl"
            alt="预览图片"
            class="preview-image" />
          <ImageUploader v-else v-model="formData.imageUrl" class="image-uploader" />
        </div>

        <!-- 右侧表单 -->
        <div class="form-container">
          <!-- Title -->
          <div class="form-item">
            <label>
              Title
              <span class="required-asterisk">*</span>
            </label>
            <el-input
              class="form-textarea"
              :maxlength="100"
              show-word-limit
              type="textarea"
              v-model="formData.title"
              :rows="2"
              placeholder="Please enter a title"></el-input>
          </div>

          <!-- Design Description -->
          <div class="form-item">
            <label>Design Description</label>
            <div class="base-textarea">
              <el-input
                class="form-textarea"
                :maxlength="100"
                show-word-limit
                type="textarea"
                v-model="formData.caption"
                :rows="5"
                placeholder="Share your creative inspiration"></el-input>
              <div class="contest" v-if="aid"># {{ contestTitle }}</div>
            </div>
          </div>

          <!-- Prompt 内容 -->
          <div v-if="props.promptMode" class="form-item">
            <label>Prompt</label>
            <div class="subtext">
              {{ formData.prompt }}
            </div>
          </div>

          <!-- Prompt Settings -->
          <div v-if="props.promptMode" class="settings">
            <div class="prompt-settings-title" @click="togglePromptSettings">
              <span>Prompt Settings</span>
              <svg
                style="cursor: pointer; transition: transform 0.3s ease"
                :style="{ transform: isPromptSettingsExpanded ? 'rotate(180deg)' : 'rotate(0)' }"
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path d="M2 5L8 11L14 5" stroke="#222222" stroke-width="1.6" />
              </svg>
            </div>
            <div v-if="isPromptSettingsExpanded" class="prompt-settings-content">
              <span>Hide Prompt</span>
              <el-switch
                style="--el-switch-on-color: #13ce66"
                v-model="formData.prompt_status_hide" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 提交成功弹窗 -->
  <el-dialog
    align-center
    v-model="showSuccessDialog"
    :show-close="false"
    :width="560"
    class="post-success-dialog">
    <div class="success-content">
      <!-- 成功图标 -->
      <div class="success-icon">
        <SvgIcon name="ai-post-success" size="80" />
      </div>

      <!-- 成功标题 -->
      <div class="success-title">Submission Successful!</div>

      <!-- 描述文本 -->
      <div class="success-description">
        {{
          aid
            ? 'Thank you for your amazing design! Share it with friends and rally support — the more votes, the higher your chance to win!'
            : 'Thank you for your beautiful design and sharing it with your friends right away!'
        }}
      </div>

      <!-- 按钮区域 -->
      <div class="success-buttons">
        <el-button type="default" class="view-btn" @click="handleViewSub">
          {{ aid ? 'View All Entries' : 'View Submissions' }}
        </el-button>
        <el-button v-hover-gradient type="primary" class="share-btn" @click="handleShare">
          Share Now
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import { FeedsAPI } from '@/api/feeds';
  import SvgIcon from '@/components/SvgIcon.vue';
  import ImageUploader from '@/components/ImageUploader.vue';
  import { useRouter } from 'vue-router';
  import CheckBox from '@/components/form/CheckBox.vue';
  import HelpIcon from '@/components/icons/ai/HelpIcon.vue';

  const router = useRouter();

  const aid = computed(() => router.currentRoute.value.query.aid as string);

  // 定义组件接收的props
  const props = withDefaults(
    defineProps<{
      prompt: string;
      // 可选的初始图片URL数组
      imageList?: string[];
      // 是否启用提示词模式
      promptMode?: boolean;
      // 活动标题
      contestTitle?: string;
    }>(),
    {
      imageList: () => [],
      promptMode: true,
      prompt: '',
      contestTitle: '',
    }
  );

  // 定义组件可以发出的事件
  const emit = defineEmits<{
    close: [];
  }>();

  const visible = ref(true);
  // 提交成功弹窗状态
  const showSuccessDialog = ref(false);
  // 存储发布成功后的feed_id
  const feedId = ref<string | null>(null);

  // 在script setup部分添加计算属性，控制按钮禁用状态
  const formData = reactive({
    title: '',
    caption: '',
    prompt: '',
    imageUrl: '',
    disable_nex: false,
    prompt_status_hide: false,
  });

  // 添加控制按钮禁用状态的变量
  const isPublishing = ref(false);

  // 添加计算属性，控制按钮禁用状态（标题为空或正在发布时禁用）
  const isPublishDisabled = computed(() => {
    return !formData.title.trim() || isPublishing.value;
  });

  // 控制prompt设置内容的显示/隐藏状态
  const isPromptSettingsExpanded = ref(false);

  // 切换prompt设置内容的显示/隐藏
  const togglePromptSettings = () => {
    isPromptSettingsExpanded.value = !isPromptSettingsExpanded.value;
  };

  // 监听props变化，更新表单数据
  watch(
    () => props.imageList,
    (newValue) => {
      if (newValue && newValue.length > 0) {
        formData.imageUrl = newValue[0];
      } else {
        formData.imageUrl = '';
      }
    },
    { immediate: true }
  );

  watch(
    () => props.prompt,
    (newValue) => {
      formData.prompt = newValue;
    },
    { immediate: true }
  );

  const publishTitle = computed(() => (props.promptMode ? 'Publish Work' : 'Upload File'));

  // 打开对话框的方法
  const open = () => {
    resetForm();
    visible.value = true;
  };

  // 关闭对话框的方法
  const close = () => {
    visible.value = false;
    // 发送close事件给父组件
    emit('close');
  };

  // 处理发布按钮点击
  // 修改handlePublish函数，使用计算属性进行检查
  const handlePublish = async () => {
    // 如果按钮被禁用，则不触发发布
    if (isPublishDisabled.value) return;

    try {
      // 设置为发布中状态
      isPublishing.value = true;

      // 直接使用表单对象构建API请求参数
      const params = {
        title: formData.title,
        caption: formData.caption,
        imgs: formData.imageUrl ? [formData.imageUrl] : [],
        thumbnail: formData.imageUrl,
        enable_nex: formData.disable_nex ? 0 : 1,
        prompt_status: formData.prompt_status_hide ? 0 : 1,
        prompt_text: formData.prompt,
        aid: aid.value || '',
      };
      // 调用发布接口
      const response = await FeedsAPI.publishFeed(params);
      // 存储返回的feed_id
      feedId.value = response.feed_id;
      visible.value = false;
      showSuccessDialog.value = true;
      // 重置表单
      resetForm();
    } catch (error) {
      ElMessage.error('Failed to publish, please try again');
    } finally {
      // 无论成功失败，都要重置发布状态
      isPublishing.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    Object.assign(formData, {
      title: '',
      caption: '',
      prompt: '',
      imageUrl: '',
      disable_nex: false,
      prompt_status_hide: false,
    });
    isPromptSettingsExpanded.value = false;
  };

  // 处理查看提交按钮点击
  const handleViewSub = () => {
    showSuccessDialog.value = false;
    // 跳转到首页并带上feed_id
    if (aid.value) {
      router.push({
        path: '/contest/detail',
        query: { aid: aid.value },
      });
    } else {
      router.push({
        path: '/',
        query: feedId.value ? { feed_id: feedId.value } : {},
      });
    }
  };

  // 处理分享按钮点击
  const handleShare = async () => {
    try {
      // 构建分享链接 - 包含域名和feed_id
      const shareLink = `${window.location.origin}/detail?feed_id=${feedId.value}`;

      // 复制的文本内容 - 增加链接地址
      const textToCopy = `This design is exceptionally beautiful — click the link now to check it out! ${shareLink}`;

      await navigator.clipboard.writeText(textToCopy);
      ElMessage.success('The content link has been copied');
    } catch (err) {
      console.error('Failed to copy text:', err);
      ElMessage.error('Failed to copy text');
    }
  };

  // 暴露方法给父组件，使其可以通过 ref 调用
  defineExpose({
    open,
    close,
  });
</script>

<style lang="scss" scoped>
  .my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
  }
  .header-left {
    font-weight: 600;
    font-style: SemiBold;
    font-size: 16px;

    line-height: 100%;
    letter-spacing: 0%;
    text-align: center;
  }

  .header-right {
    display: flex;
    align-items: center;
  }

  .help-icon {
    margin-left: 4px;
  }

  .close-icon {
    cursor: pointer;
    position: absolute;
    right: -30px;
    top: 0px;
  }

  .publish-btn {
    margin-left: 24px;
    width: 124px;
    height: 40px;

    font-weight: 500;
    font-style: Medium;
    font-size: 16px;
    line-height: 100%;
    letter-spacing: 0%;
    border: none;
    background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);
    .svg-icon {
      margin-left: 8px;
    }
    &:hover:not(:disabled) {
      background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
    }
    &:disabled {
      background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);
      opacity: 0.5;
    }
  }

  .dialog-content {
    padding-bottom: 8px;
  }

  .content-row {
    display: flex;
    gap: 24px;
  }

  .image-container {
    width: 560px;
    height: 560px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    .image-uploader {
      height: 100%;
      :deep(.el-upload-dragger) {
        height: 460px;
      }
    }
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .form-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .form-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .form-item label {
    font-size: 16px;
    font-weight: 500;
    color: #222222;

    line-height: 100%;
  }

  .form-item .subtext {
    font-weight: 400;
    font-size: 14px;
    line-height: 150%;
  }

  .required-asterisk {
    color: #ff4d4f;
    margin-left: 2px;
  }

  .settings {
    cursor: pointer;

    font-weight: 500;
    font-style: Medium;
    font-size: 14px;
    line-height: 100%;
    letter-spacing: 0%;
    color: #222222;
  }

  .prompt-settings-title {
    color: #222222;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
  }
  .prompt-settings-content {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    color: #7a7a7a;
    gap: 8px;
  }

  .base-textarea {
    position: relative;
    .contest {
      position: absolute;
      left: 16px;
      bottom: 8px;
      padding: 4px 8px;
      border-radius: 4px;
      background: #e1e2e3;
      color: #222222;
    }
  }
  .form-textarea {
    :deep(.el-textarea__inner) {
      width: 100%;
      padding: 8px 16px;
      border-radius: 8px;
      resize: none;
      outline: none;
      background-color: #f8f8f8;

      font-weight: 400;
      font-size: 14px;
      color: #222222;
      border: none;
      box-shadow: none;
      &::placeholder {
        color: #7a7a7a;
      }
      &:focus {
        border: none;
        box-shadow: none;
      }
    }
    :deep(.el-input__count) {
      background: transparent;
    }
  }
  .success-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .success-icon {
    margin-bottom: 8px;
  }

  .success-title {
    font-size: 24px;
    font-weight: 600;
    color: #222222;
    margin-bottom: 16px;
  }

  .success-description {
    font-size: 16px;
    color: #7a7a7a;
    margin-bottom: 40px;
    text-align: left;
  }

  .success-buttons {
    display: flex;
    gap: 16px;
    width: 100%;
    height: 48px;
  }

  .view-btn {
    flex: 1;
    background: #fbe6db;
    color: #f76b1b;
    height: 48px;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    font-size: 18px;
    &:hover {
      background: #f9d9c7;
    }
  }

  .share-btn {
    font-size: 18px;
    flex: 1;
    background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);
    height: 48px;
    border: none;
    border-radius: 8px;
    font-weight: 500;
  }
</style>

<style lang="scss">
  /* 对 el-dialog 根节点本身依然有效 */
  .post-success-dialog {
    border-radius: 8px;
    padding: 24px;
    .el-dialog__header {
      padding-bottom: 0px;
    }
  }
</style>
